package middleware.llvm.instruction;

import middleware.llvm.value.IRType;
import middleware.llvm.value.Value;

import java.io.PrintStream;

/**
 * 分配指令，用于在栈上分配内存。
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class AllocaInstruction extends Instruction {

    public AllocaInstruction(IRType dataType) {
        super(dataType.clone().ptr(dataType.getPtrNum() + 1)); // the type of alloca var is actually the address of the data
    }

    public IRType getDataType() {
        return getType().clone().ptr(getType().getPtrNum() - 1);
    }

    @Override
    public void replaceOperand(int pos, Value newOperand) {
        super.replaceOperand(pos, newOperand);
    }

    @Override
    public void dump(PrintStream out) {
        var dataType = getType().clone().ptr(getType().getPtrNum() - 1); // remove pointer
        out.printf("  %s = alloca %s\n", getName(), dataType);
    }
}
